/*
 * User: avishay
 * Date: Feb 11, 2007
 *
 * Copyright (2005) IDI. All rights reserved.
 * This software is a proprietary information of Israeli Direct Insurance.
 * Created by IntelliJ IDEA.
 */
package com.idi.maven.plugins;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;

/**
 *
 */
public class ModuleProperties {

	public static final String MODULE_PROPERTIES = "module.properties";
	private static final String LEGACY_MODULE_NAME = "legacy.module.name";

	private Properties properties;

	public ModuleProperties(final File basedir, final Log log) throws MojoExecutionException {
		parse(basedir,log);
	}

	private void parse(final File basedir, final Log log) throws MojoExecutionException {
		final File file = new File(basedir, MODULE_PROPERTIES);
		if (file.exists() && !file.isDirectory()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				properties = new Properties();
				properties.load(fis);
			} catch (Exception e) {
				throwException(e);
			} finally {
				try {
					assert fis != null;
					fis.close();
				} catch (IOException e) {
					throwException(e);
				}
			}
		} else {
			log.warn(MessageFormat.format("Plugin cannot continue, [{0}] does not exist in [{1}]", MODULE_PROPERTIES, basedir));
		}
	}

	private void throwException(final Exception exception) throws MojoExecutionException {
		throw new MojoExecutionException("failed loading  " + MODULE_PROPERTIES, exception);
	}

	public String getProperty(final String propertyName) {
		return wasParsed() ? properties.getProperty(propertyName) : null;
	}

	public String getLegacyModuleName() {
		return getProperty(LEGACY_MODULE_NAME);
	}

	public boolean wasParsed() {
		return properties != null;
	}
}